#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QFileInfoList>
#include <QFileInfo>
#include <QPixmap>
#include <QDebug>
#include <QMetaType>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QDateTime>
#include <QTimer>
#include <QIcon>

using namespace XVL;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , threadManager_(nullptr)
    , totalCount_(0)
    , currIndex_(0)
    , isPaused_(true)
    , baseFontSize_(10)
    , countMode_(0)
    , timer_(nullptr)
    , totalLimit_(30)
    , leftLimit_(20)
    , rightLimit_(20)
    , totalNum_(0)
    , leftNum_(0)
    , rightNum_(0)
{
    ui->setupUi(this);
    setWindowTitle("分析图片黑色区域");
    setWindowIcon(QIcon(":/images/logo.png"));
    setMinimumSize(805, 720);
    // 图片文件夹路径
    path_ = "F:/phase2/TA03-4S";
    // 初始化界面
    initMainwindow();
    // showMaximized();
    // 加载保存的设置
    loadSettings();
    // 初始化线程管理对象
    threadManager_ = new ThreadManager(this);
    timer_ = new QTimer(this);

    // 将加载的设置应用到线程管理器
    threadManager_->setCountMode(countMode_);
    threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);

    // 初始化信号槽
    initSlots();

    // 设置图片文件夹的路径，并启动三个子线程
    threadManager_->setPathAndStartThread(path_);
}

MainWindow::~MainWindow()
{
    // 保存设置
    saveSettings();
    // 安全停止处理线程
    if (threadManager_)
    {
        threadManager_->stopProcessing();
        // 等待足够的时间让三个子线程都能完全退出
        QThread::msleep(1000);
    }
    delete ui;
}

void MainWindow::initMainwindow()
{
    // 创建中心部件
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    // 创建主垂直布局
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    // 第一行：按钮区域
    QHBoxLayout *topButtonLayout = new QHBoxLayout();
    topButtonLayout->setSpacing(20);

    QString btnStyle = "QPushButton { border: none; background-color: transparent; }";
    btnStyle += "QPushButton:hover { background-color: rgba(200, 200, 200, 50); border-radius: 4px; }";
    btnStyle += "QPushButton:pressed { background-color: rgba(150, 150, 150, 80); }";
    btnStyle += "QPushButton:disabled { opacity: 0.5; }";
    QString editStyle = "QLineEdit { border: none; border-radius: 4px; }";


    // 上一张按钮
    prevButton_ = new QPushButton(this);
    prevButton_->setIcon(QIcon(":/images/pre.png"));
    prevButton_->setIconSize(QSize(36, 36));
    prevButton_->setToolTip("上一张图片");
    prevButton_->setStyleSheet(btnStyle);
    // 下一张按钮
    nextButton_ = new QPushButton(this);
    nextButton_->setIcon(QIcon(":/images/next.png"));
    nextButton_->setIconSize(QSize(36, 36));
    nextButton_->setToolTip("下一张图片");
    nextButton_->setStyleSheet(btnStyle);
    // 开始按钮
    keepButton_ = new QPushButton(this);
    keepButton_->setIcon(QIcon(":/images/start.png"));
    keepButton_->setIconSize(QSize(36, 36));
    keepButton_->setToolTip("开始连续遍历图片");
    keepButton_->setStyleSheet(btnStyle);
    // 暂停按钮
    pauseButton_ = new QPushButton(this);
    pauseButton_->setIcon(QIcon(":/images/stop.png"));
    pauseButton_->setIconSize(QSize(36, 36));
    pauseButton_->setToolTip("暂停连续遍历图片");
    pauseButton_->setStyleSheet(btnStyle);
    // 切换模式按钮
    modeButton_ = new QPushButton(this);
    modeButton_->setIcon(QIcon(":/images/switch.png"));
    modeButton_->setIconSize(QSize(36, 36));
    modeButton_->setToolTip("切换当前模式");
    modeButton_->setStyleSheet(btnStyle);
    // 模式标签
    modeLabel_ = new QLabel(this);

    // 添加到顶部按钮布局
    topButtonLayout->addWidget(prevButton_);
    topButtonLayout->addWidget(nextButton_);
    topButtonLayout->addWidget(keepButton_);
    topButtonLayout->addWidget(pauseButton_);
    topButtonLayout->addWidget(modeButton_);
    topButtonLayout->addStretch(1);
    topButtonLayout->addWidget(modeLabel_);
    topButtonLayout->addStretch(1);

    mainLayout->addLayout(topButtonLayout);

    // 带轮廓的图片展示 GroupBox
    contourGroupBox_ = new QGroupBox("带轮廓的图片展示", this);
    QVBoxLayout *contourLayout = new QVBoxLayout(contourGroupBox_);
    contourLayout->setSpacing(10);

    // statusLabel_ 放在最上方
    statusLabel_ = new QLabel(this);
    statusLabel_->setAlignment(Qt::AlignCenter);
    statusLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    contourLayout->addWidget(statusLabel_);

    // imageLabel_ 在statusLabel_下方
    imageLabel_ = new QLabel(centralWidget);
    imageLabel_->setStyleSheet("border: 1px solid #ccc;");
    imageLabel_->setAlignment(Qt::AlignCenter);
    imageLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    imageLabel_->setScaledContents(true);
    contourLayout->addWidget(imageLabel_);

    mainLayout->addWidget(contourGroupBox_);

    // 下方左右两个GroupBox的容器
    QHBoxLayout *bottomContainerLayout = new QHBoxLayout();
    bottomContainerLayout->setSpacing(20);

    // 左侧：计数结果 GroupBox
    countResultGroupBox_ = new QGroupBox("计数结果", this);
    QVBoxLayout *countLayout = new QVBoxLayout(countResultGroupBox_);
    countLayout->setSpacing(10);
    countLayout->setContentsMargins(10, 10, 10, 10);

    // countLabel_ 上限标签在最上方
    countLabel_ = new QLabel(this);
    countLayout->addWidget(countLabel_);

    limitRowLayout1 = new QHBoxLayout();
    limitRowLayout2 = new QHBoxLayout();
    limitRowLayout3 = new QHBoxLayout();

    totalLimitTag_ = new QLabel("整体个数上限: ", this);
    leftLimitTag_ = new QLabel("左侧个数上限: ", this);
    rightLimitTag_ = new QLabel("右侧个数上限: ", this);

    totalLineEdit_ = new QLineEdit();
    totalLineEdit_->setStyleSheet(editStyle);
    totalLineEdit_->hide();
    leftLineEdit_ = new QLineEdit();
    leftLineEdit_->setStyleSheet(editStyle);
    leftLineEdit_->hide();
    rightLineEdit_ = new QLineEdit();
    rightLineEdit_->setStyleSheet(editStyle);
    rightLineEdit_->hide();

    totalLimitLabel_ = new QLabel(QString::number(totalLimit_));
    totalLimitLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    leftLimitLabel_ = new QLabel(QString::number(leftLimit_));
    leftLimitLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    rightLimitLabel_ = new QLabel(QString::number(rightLimit_));
    rightLimitLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    totalModBtn_ = new QPushButton(this);
    totalModBtn_->setIcon(QIcon(":/images/modify.png"));
    totalModBtn_->setIconSize(QSize(25, 25));
    totalModBtn_->setToolTip("点击修改上限值");
    totalModBtn_->setStyleSheet(btnStyle);

    leftModBtn_ = new QPushButton(this);
    leftModBtn_->setIcon(QIcon(":/images/modify.png"));
    leftModBtn_->setIconSize(QSize(25, 25));
    leftModBtn_->setToolTip("点击修改上限值");
    leftModBtn_->setStyleSheet(btnStyle);

    rightModBtn_ = new QPushButton(this);
    rightModBtn_->setIcon(QIcon(":/images/modify.png"));
    rightModBtn_->setIconSize(QSize(25, 25));
    rightModBtn_->setToolTip("点击修改上限值");
    rightModBtn_->setStyleSheet(btnStyle);

    totalSubBtn_ = new QPushButton();
    totalSubBtn_->setIcon(QIcon(":/images/submit.png"));
    totalSubBtn_->setIconSize(QSize(25, 25));
    totalSubBtn_->setToolTip("点击确认修改");
    totalSubBtn_->setStyleSheet(btnStyle);
    totalSubBtn_->hide();

    leftSubBtn_ = new QPushButton();
    leftSubBtn_->setIcon(QIcon(":/images/submit.png"));
    leftSubBtn_->setIconSize(QSize(25, 25));
    leftSubBtn_->setToolTip("点击确认修改");
    leftSubBtn_->setStyleSheet(btnStyle);
    leftSubBtn_->hide();

    rightSubBtn_ = new QPushButton();
    rightSubBtn_->setIcon(QIcon(":/images/submit.png"));
    rightSubBtn_->setIconSize(QSize(25, 25));
    rightSubBtn_->setToolTip("点击确认修改");
    rightSubBtn_->setStyleSheet(btnStyle);
    rightSubBtn_->hide();

    limitRowLayout1->addWidget(totalLimitTag_);
    limitRowLayout1->addWidget(totalLimitLabel_);
    limitRowLayout1->addWidget(totalModBtn_);

    limitRowLayout2->addWidget(leftLimitTag_);
    limitRowLayout2->addWidget(leftLimitLabel_);
    limitRowLayout2->addWidget(leftModBtn_);

    limitRowLayout3->addWidget(rightLimitTag_);
    limitRowLayout3->addWidget(rightLimitLabel_);
    limitRowLayout3->addWidget(rightModBtn_);

    countLayout->addLayout(limitRowLayout1);
    countLayout->addLayout(limitRowLayout2);
    countLayout->addLayout(limitRowLayout3);

    // 添加伸缩项，将上方控件向上推，为倒计时控件预留空间
    countLayout->addStretch(1);

    // 倒计时相关控件（最下方，固定高度区域）
    QHBoxLayout *countdownLayout = new QHBoxLayout();
    countdownLayout->setSpacing(5);
    // 为倒计时区域设置固定高度
    QWidget *countdownContainer = new QWidget(this);
    countdownContainer->setFixedHeight(40);  // 固定高度，不会挤压上方的控件
    QHBoxLayout *containerLayout = new QHBoxLayout(countdownContainer);
    containerLayout->setContentsMargins(0, 0, 0, 0);

    countdownLabel_ = new QLabel("暂停倒计时：", this);
    countdownLabel_->setVisible(false);  // 默认隐藏
    countdownLcd_ = new QLCDNumber(2, this);
    countdownLcd_->setSegmentStyle(QLCDNumber::Flat);
    countdownLcd_->setStyleSheet("border: none; color: red;");
    countdownLcd_->setVisible(false);    // 默认隐藏

    containerLayout->addWidget(countdownLabel_);
    containerLayout->addWidget(countdownLcd_);
    containerLayout->addStretch(1);

    countdownLayout->addWidget(countdownContainer);
    countLayout->addLayout(countdownLayout);

    // 设置布局伸缩策略，确保下方预留空间
    countLayout->setStretch(0, 2);  // countLabel_
    countLayout->setStretch(1, 1);  // 第一行上限
    countLayout->setStretch(2, 1);  // 第二行上限
    countLayout->setStretch(3, 1);  // 第三行上限
    countLayout->setStretch(4, 1);  // 倒计时区域（固定空间）

    bottomContainerLayout->addWidget(countResultGroupBox_, 1);  // 左侧占1份宽度

    // 右侧：各区域周长、面积展示 GroupBox
    periAreaGroupBox_ = new QGroupBox("各区域周长、面积展示", this);
    QVBoxLayout *periAreaLayout = new QVBoxLayout(periAreaGroupBox_);

    // showLabel_ 放在这个groupbox中
    showLabel_ = new QLabel(this);
    showLabel_->setAlignment(Qt::AlignCenter);
    showLabel_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    periAreaLayout->addWidget(showLabel_);

    bottomContainerLayout->addWidget(periAreaGroupBox_, 2);  // 右侧占2份宽度

    mainLayout->addLayout(bottomContainerLayout);

    // 初始化模式显示
    updateModeDisplay();

    // 初始状态设置
    pauseButton_->setEnabled(false);
    countdownLabel_->setVisible(false);
    countdownLcd_->setVisible(false);
}

void MainWindow::initSlots()
{
    // 连接信号槽
    connect(threadManager_, &ThreadManager::imageProcessed, this, &MainWindow::onImageProcessed);
    connect(threadManager_, &ThreadManager::processError, this, &MainWindow::onProcessError);
    connect(threadManager_, &ThreadManager::queueFull, this, &MainWindow::onQueueFull);
    connect(threadManager_, &ThreadManager::totalCountUpdated, this, &MainWindow::onTotalCount);
    connect(pauseButton_, &QPushButton::clicked, this, &MainWindow::onPauseButtonClicked);
    connect(keepButton_, &QPushButton::clicked, this, &MainWindow::onKeepButtonClicked);
    connect(prevButton_, &QPushButton::clicked, this, &MainWindow::onPrevButtonClicked);
    connect(nextButton_, &QPushButton::clicked, this, &MainWindow::onNextButtonClicked);
    // 模式相关信号槽
    connect(modeButton_, &QPushButton::clicked, this, &MainWindow::onModeButtonClicked);
    // 超过上限信号槽连接
    connect(threadManager_, &ThreadManager::LimitExceeded, this, &MainWindow::onLimitExceeded);
    // 计数更新信号槽连接
    connect(threadManager_, &ThreadManager::countUpdated, this, &MainWindow::onCountUpdated);
    // 倒计时信号
    connect(threadManager_, &ThreadManager::startCountdown, this, &MainWindow::onStartCountdown);
    connect(timer_, &QTimer::timeout, this, &MainWindow::onTimeout);
    // 修改上限值相关信号槽
    connect(totalModBtn_, &QPushButton::clicked, this, &MainWindow::onTotalModBtn);
    connect(leftModBtn_, &QPushButton::clicked, this, &MainWindow::onLeftModBtn);
    connect(rightModBtn_, &QPushButton::clicked, this, &MainWindow::onRightModBtn);
    connect(totalSubBtn_, &QPushButton::clicked, this, &MainWindow::onTotalSubBtn);
    connect(leftSubBtn_, &QPushButton::clicked, this, &MainWindow::onLeftSubBtn);
    connect(rightSubBtn_, &QPushButton::clicked, this, &MainWindow::onRightSubBtn);
}

void MainWindow::loadSettings()
{
    QSettings settings("XINJEVision", "ImageAnalysis");

    // 加载统计模式
    countMode_ = settings.value("countMode", 0).toInt();

    // 加载上限值
    totalLimit_ = settings.value("totalLimit", 30).toInt();
    leftLimit_ = settings.value("leftLimit", 20).toInt();
    rightLimit_ = settings.value("rightLimit", 20).toInt();

    // 更新界面显示
    totalLimitLabel_->setText(QString::number(totalLimit_));
    leftLimitLabel_->setText(QString::number(leftLimit_));
    rightLimitLabel_->setText(QString::number(rightLimit_));

    // 更新模式显示
    updateModeDisplay();
}

void MainWindow::saveSettings()
{
    QSettings settings("XINJEVision", "ImageAnalysis");

    // 保存统计模式
    settings.setValue("countMode", countMode_);

    // 保存上限值
    settings.setValue("totalLimit", totalLimit_);
    settings.setValue("leftLimit", leftLimit_);
    settings.setValue("rightLimit", rightLimit_);

    // 立即写入
    settings.sync();
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    // 先调用父类的方法
    QMainWindow::resizeEvent(event);

    // 根据窗口宽度计算合适的字体大小
    int newFontSize = baseFontSize_ + (width() / 100);
    // 限制大小，避免太大
    newFontSize = qMin(newFontSize, 25);

    QFont font = statusLabel_->font();
    font.setPointSize(newFontSize);
    // groupBox的字体略小于其他字体
    QFont groupFont = statusLabel_->font();
    groupFont.setPointSize(newFontSize - 5);

    // 应用新字体大小到所有需要自适应的控件
    statusLabel_->setFont(font);
    showLabel_->setFont(font);
    pauseButton_->setFont(font);
    keepButton_->setFont(font);
    prevButton_->setFont(font);
    nextButton_->setFont(font);
    modeButton_->setFont(font);
    modeLabel_->setFont(font);
    countLabel_->setFont(font);
    countdownLcd_->setFont(font);
    countdownLabel_->setFont(font);
    contourGroupBox_->setFont(groupFont);
    countResultGroupBox_->setFont(groupFont);
    periAreaGroupBox_->setFont(groupFont);
    totalLimitTag_->setFont(groupFont);
    leftLimitTag_->setFont(groupFont);
    rightLimitTag_->setFont(groupFont);
    totalLimitLabel_->setFont(groupFont);
    leftLimitLabel_->setFont(groupFont);
    rightLimitLabel_->setFont(groupFont);
    totalLineEdit_->setFont(groupFont);
    leftLineEdit_->setFont(groupFont);
    rightLineEdit_->setFont(groupFont);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveSettings();
    QMainWindow::closeEvent(event);
}

void MainWindow::onImageProcessed(const ProcessResult &result)
{
    currIndex_ = result.currentIndex;
    // 显示处理结果
    displayResults(result);
}

void MainWindow::onProcessError(const QString& message)
{
    // 图片上方显示错误信息
    statusLabel_->setText(QString("处理错误: ") + message);
}

void MainWindow::onPauseButtonClicked()
{
    // 点击暂停按钮后，默认处于手动模式
    threadManager_->setManualMode(true);
    // 暂停两个线程
    threadManager_->pauseProcessing();
    isPaused_ = true;
    updateButtonStates(false);
    // 暂停后隐藏倒计时标签和LCD
    countdownLabel_->setVisible(false);
    countdownLcd_->setVisible(false);
}

void MainWindow::onKeepButtonClicked()
{
    threadManager_->setManualMode(false);
    // 继续两个线程
    threadManager_->keepProcessing();
    isPaused_ = false;
    updateButtonStates(true);
}

void MainWindow::onQueueFull()
{
    // 5秒内只弹窗警告一次
    static qint64 lastWarnTime = 0;
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    if (currentTime - lastWarnTime > 5000)
    {
        QMessageBox::warning(nullptr, "警告", "图片队列已满");
        lastWarnTime = currentTime;
    }
}

void MainWindow::onTotalCount(const int count)
{
    totalCount_ = count;
}

void MainWindow::onPrevButtonClicked()
{
    if(totalCount_ == 0)
    {
        return;
    }

    currIndex_--;
    if(currIndex_ < 0)
    {
        currIndex_ = totalCount_ - 1;
    }
    threadManager_->setManualMode(true);
    threadManager_->setCurrManualIndex(currIndex_);
}

void MainWindow::onNextButtonClicked()
{
    if(totalCount_ == 0)
    {
        return;
    }

    currIndex_++;
    if(currIndex_ == totalCount_)
    {
        currIndex_ = 0;
    }
    threadManager_->setManualMode(true);
    threadManager_->setCurrManualIndex(currIndex_);
}

// 模式切换按钮点击事件
void MainWindow::onModeButtonClicked()
{
    // 切换模式
    countMode_ = (countMode_ == 0) ? 1 : 0;

    // 通知线程管理器
    threadManager_->setCountMode(countMode_);
    updateModeDisplay();

    // 保存设置
    saveSettings();
}

void MainWindow::onLimitExceeded()
{
    statusBar()->showMessage("当前超过上限值", 1000);
}

void MainWindow::onCountUpdated(const CountResult &result)
{
    // 更新本地计数值
    totalNum_ = result.totalCount;
    leftNum_ = result.leftCount;
    rightNum_ = result.rightCount;
    // 更新界面显示
    updateModeDisplay();
}

void MainWindow::onStartCountdown(int seconds)
{
    // 同时显示标签和LCD
    countdownLabel_->setVisible(true);
    countdownLcd_->display(seconds);
    countdownLcd_->setVisible(true);

    // 如果有正在运行的定时器，则停止
    if (timer_->isActive())
    {
        timer_->stop();
    }

    timer_->start(1000); // 每秒触发一次
}

void MainWindow::onTimeout()
{
    // 获取当前剩余秒数，从LCD读取
    int remaining = countdownLcd_->intValue();
    remaining--;
    countdownLcd_->display(remaining);

    if (remaining <= 0)
    {
        // 停止定时器
        timer_->stop();
        // 隐藏标签和LCD
        countdownLabel_->setVisible(false);
        countdownLcd_->setVisible(false);
    }
}

void MainWindow::onCountLabelClicked()
{
    if(!isPaused_)
    {
        return;
    }

    if (countMode_ == 0)
    {
        setTotalLimit();
    }
    else
    {
        setLeftRightLimit();
    }
}

void MainWindow::onTotalModBtn()
{
    // 隐藏 Label 和  ModBtn
    totalModBtn_->hide();
    totalLimitLabel_->hide();
    limitRowLayout1->removeWidget(totalModBtn_);
    limitRowLayout1->removeWidget(totalLimitLabel_);
    // 显示 edit 和 SubBtn
    totalLineEdit_->show();
    totalSubBtn_->show();
    limitRowLayout1->addWidget(totalLineEdit_);
    limitRowLayout1->addWidget(totalSubBtn_);
    totalLineEdit_->setText(totalLimitLabel_->text());
}

void MainWindow::onLeftModBtn()
{
    // 隐藏 Label 和  ModBtn
    leftModBtn_->hide();
    leftLimitLabel_->hide();
    limitRowLayout2->removeWidget(leftModBtn_);
    limitRowLayout2->removeWidget(leftLimitLabel_);
    // 显示 edit 和 SubBtn
    leftLineEdit_->show();
    leftSubBtn_->show();
    limitRowLayout2->addWidget(leftLineEdit_);
    limitRowLayout2->addWidget(leftSubBtn_);
    leftLineEdit_->setText(leftLimitLabel_->text());
}

void MainWindow::onRightModBtn()
{
    // 隐藏 Label 和  ModBtn
    rightModBtn_->hide();
    rightLimitLabel_->hide();
    limitRowLayout3->removeWidget(rightModBtn_);
    limitRowLayout3->removeWidget(rightLimitLabel_);
    // 显示 edit 和 SubBtn
    rightLineEdit_->show();
    rightSubBtn_->show();
    limitRowLayout3->addWidget(rightLineEdit_);
    limitRowLayout3->addWidget(rightSubBtn_);
    rightLineEdit_->setText(rightLimitLabel_->text());
}

void MainWindow::onTotalSubBtn()
{
    // 隐藏 edit 和 SubBtn
    totalSubBtn_->hide();
    totalLineEdit_->hide();
    limitRowLayout1->removeWidget(totalSubBtn_);
    limitRowLayout1->removeWidget(totalLineEdit_);
    // 显示 Label 和 ModBtn
    totalLimitLabel_->show();
    totalModBtn_->show();
    limitRowLayout1->addWidget(totalLimitLabel_);
    limitRowLayout1->addWidget(totalModBtn_);
    totalLimit_ = totalLineEdit_->text().toInt();
    totalLimitLabel_->setText(QString::number(totalLimit_));
    // 更新线程管理器的上限值
    threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);
    updateModeDisplay();
    // 保存设置
    saveSettings();
}

void MainWindow::onLeftSubBtn()
{
    // 隐藏 edit 和 SubBtn
    leftSubBtn_->hide();
    leftLineEdit_->hide();
    limitRowLayout2->removeWidget(leftSubBtn_);
    limitRowLayout2->removeWidget(leftLineEdit_);
    // 显示 Label 和 ModBtn
    leftLimitLabel_->show();
    leftModBtn_->show();
    limitRowLayout2->addWidget(leftLimitLabel_);
    limitRowLayout2->addWidget(leftModBtn_);
    leftLimit_ = leftLineEdit_->text().toInt();
    leftLimitLabel_->setText(QString::number(leftLimit_));
    // 更新线程管理器的上限值
    threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);
    updateModeDisplay();
    // 保存设置
    saveSettings();
}

void MainWindow::onRightSubBtn()
{
    // 隐藏 edit 和 SubBtn
    rightSubBtn_->hide();
    rightLineEdit_->hide();
    limitRowLayout3->removeWidget(rightSubBtn_);
    limitRowLayout3->removeWidget(rightLineEdit_);
    // 显示 Label 和 ModBtn
    rightLimitLabel_->show();
    rightModBtn_->show();
    limitRowLayout3->addWidget(rightLimitLabel_);
    limitRowLayout3->addWidget(rightModBtn_);
    rightLimit_ = rightLineEdit_->text().toInt();
    rightLimitLabel_->setText(QString::number(rightLimit_));
    // 更新线程管理器的上限值
    threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);
    updateModeDisplay();
    // 保存设置
    saveSettings();
}

void MainWindow::updateModeDisplay()
{
    if (countMode_ == 0)
    {
        modeLabel_->setText("当前模式: 整体统计个数");
        countLabel_->setText(QString("总个数: %1 (上限: %2)").arg(totalNum_).arg(totalLimit_));
    }
    else
    {
        modeLabel_->setText("当前模式: 左右统计个数");
        countLabel_->setText(QString("左侧个数: %1 (上限: %2)\n右侧个数: %3 (上限: %4)").arg(leftNum_, 2).arg(leftLimit_).arg(rightNum_, 2).arg(rightLimit_));
    }
}

void MainWindow::setTotalLimit()
{
    // 创建对话框
    QDialog dialog(this);
    dialog.setWindowTitle("设置整体个数上限");
    // 布局
    QFormLayout form(&dialog);
    // 创建输入框并设置初始值
    QLineEdit *totalEdit = new QLineEdit(QString::number(totalLimit_), &dialog);
    // 限制只能输入数字，0~100
    totalEdit->setValidator(new QIntValidator(0, 100, totalEdit));
    form.addRow("请输入总数上限(0-100): ", totalEdit);
    // 添加确认按钮
    QPushButton *okButton = new QPushButton("确定", &dialog);
    form.addRow(okButton);
    // 连接按钮点击信号与对话框确认
    connect(okButton, &QPushButton::clicked, &dialog, &QDialog::accept);
    // 处理用户输入
    if (dialog.exec() == QDialog::Accepted)
    {
        int inputValue = totalEdit->text().toInt();
        // 验证输入范围
        if (inputValue > 100)
        {
            QMessageBox::warning(this, "范围错误", "请输入0-100之间的整数");
        }
        else
        {
            totalLimit_ = inputValue;
            // 更新线程管理器的上限值
            threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);
        }
    }
    updateModeDisplay();
}

void MainWindow::setLeftRightLimit()
{
    QDialog dialog(this);
    dialog.setWindowTitle("设置左右个数上限");

    QFormLayout form(&dialog);

    QLineEdit *leftEdit = new QLineEdit(QString::number(leftLimit_), &dialog);
    QLineEdit *rightEdit = new QLineEdit(QString::number(rightLimit_), &dialog);

    leftEdit->setValidator(new QIntValidator(0, 100, leftEdit));
    rightEdit->setValidator(new QIntValidator(0, 100, rightEdit));

    form.addRow("请输入左侧个数上限(0-100): ", leftEdit);
    form.addRow("请输入右侧个数上限(0-100): ", rightEdit);

    QPushButton *okButton = new QPushButton("确定", &dialog);
    form.addRow(okButton);

    connect(okButton, &QPushButton::clicked, &dialog, &QDialog::accept);

    if (dialog.exec() == QDialog::Accepted)
    {
        int inputLeft = leftEdit->text().toInt();
        int inputRight = rightEdit->text().toInt();
        if(inputLeft > 100 || inputRight > 100)
        {
            QMessageBox::warning(this, "范围错误", "请输入0-100之间的整数");
        }
        else
        {
            leftLimit_ = inputLeft;
            rightLimit_ = inputRight;
            // 更新线程管理器的上限值
            threadManager_->setLimits(totalLimit_, leftLimit_, rightLimit_);
        }
    }
    updateModeDisplay();
}

void MainWindow::displayResults(const ProcessResult &result)
{
    int percent = static_cast<int>((static_cast<double>(result.currentIndex + 1) / totalCount_) * 100);
    QString statusText;
    statusText = QString("当前是第 %1 张图片(共 %2 张)  |  进度 %3%  |  区域数 %4")
                     .arg(result.currentIndex + 1)
                     .arg(totalCount_, 2)
                     .arg(percent)
                     .arg(result.periAndArea.size());
    // 显示状态标签
    statusLabel_->setText(statusText);

    // 显示蓝色轮廓图片标签
    imageLabel_->setPixmap(result.processedImage);

    // 显示区域、周长、面积标签
    const vector<pair<int, int>>& periAndArea = result.periAndArea;
    QString str;
    // 预分配空间
    str.reserve(static_cast<int>(periAndArea.size() * 250));
    for (int i = 0; i < periAndArea.size(); ++i)
    {
        str += QString("区域%1: 周长为 %2, 面积为 %3\n").arg(i + 1).arg(periAndArea[i].first, 3).arg(periAndArea[i].second, 4);
    }
    showLabel_->setText(str);
}

void MainWindow::updateButtonStates(bool isRunning)
{
    // 更新按钮状态
    pauseButton_->setEnabled(isRunning);
    keepButton_->setEnabled(!isRunning);

    // 上一张按钮、下一张按钮和模式切换按钮只在暂停状态下可用
    prevButton_->setEnabled(!isRunning);
    nextButton_->setEnabled(!isRunning);
    modeButton_->setEnabled(!isRunning);
    totalModBtn_->setEnabled(!isRunning);
    leftModBtn_->setEnabled(!isRunning);
    rightModBtn_->setEnabled(!isRunning);
    totalSubBtn_->setEnabled(!isRunning);
    leftSubBtn_->setEnabled(!isRunning);
    rightSubBtn_->setEnabled(!isRunning);
}
